package spring.cloud.tasks.client.item_task_processor.pooled.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import spring.cloud.tasks.client.item_task_processor.TaskExecuteLog;
import spring.cloud.tasks.client.item_task_processor.pooled.TaskExecuteLogPooled;
import spring.cloud.tasks.client.item_task_processor.pooled.timer_task.TimerTask;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Slf4j
public class TaskExecuteLogPooledImpl implements TaskExecuteLogPooled, ApplicationListener {
    private static final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    private ConcurrentLinkedQueue<TaskExecuteLog> queue = new ConcurrentLinkedQueue();
    private Runnable timerTask = new TimerTask("", "") {
        @Override
        public void process() throws Exception {
            int i = 0;
            List<TaskExecuteLog> executeLogList = new ArrayList<TaskExecuteLog>();
            Long startTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - startTime < 1000) {
                if (queue.isEmpty()) {
                    Thread.sleep(100);
                    continue;
                }
                i++;
                TaskExecuteLog executeLog = queue.poll();
                executeLogList.add(executeLog);
            }

            if (executeLogList.size() == 0) {
                return;
            }
            log.info("执行日志数据发送完成,total:{}", i);
        }
    };

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        scheduledExecutorService.scheduleWithFixedDelay(timerTask, 1000, 1000, TimeUnit.SECONDS);
    }

    @Override
    public void add(TaskExecuteLog taskExecuteLog) {
        queue.add(taskExecuteLog);
    }

}
